import random

from django.shortcuts import render

# Create your views here.
# GET /sms_codes/(?P<mobile>1[3-9]\d{9})/

# url('^sms_codes/(?P<mobile>1[3-9]\d{9})/$', views.SMSCodeView.as_view()),
from django_redis import get_redis_connection
from rest_framework import status
from rest_framework.response import Response
from rest_framework.views import APIView

from meiduo_mall.meiduo_mall.apps.verifications import constants
from meiduo_mall.meiduo_mall.libs.yuntongxun.sms import CCP


class SMSCodeView(APIView):
    """短信验证码"""
    def get(self,request,mobile):
        # 判断图片验证码。判断是否在60s内
        redis_conn = get_redis_connection('verify_codes')
        send_flag =redis_conn.get('send_flag_%s' %mobile)

        if send_flag:
            return Response({"message": "请求次数过于频繁"},status=status.HTTP_400_BAD_REQUEST)
        # 生成短信验证码
        sms_code='%06d'% random.randint(0,999999)
        pl =redis_conn.pipeline()
        pl.setex('sms_%'% mobile,constants.SMS_CODE_REDIS_EXPIRES, sms_code)
        pl.setex('send_flag_%s'%mobile,constants.SEND_SMS_CODE_INTERVAL, 1)
        pl.execute()
        sms_code_expires = constants.SMS_CODES_REDIS_EXPIRES // 60
        try:
            ccp =CCP()
            res = ccp.send_template_sms(mobile,[sms_code,sms_code_expires],constants.SMS_CODE_TEMP_ID)
        except Exception as e:
            return  Response({"message": "发送短信异常"}, status=status.HTTP_503_SERVICE_UNAVAILABLE)

        if res !=0:
            return Response({"message": "发送短信失败"}, status=status.HTTP_503_SERVICE_UNAVAILABLE)

        return  Response({'message':'ok'})